package com.hjw.service.impl;

import com.hjw.dao.TypeDao;
import com.hjw.entity.Type;
import com.hjw.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>Project:Academic - TypeServiceImpl<p>
 *
 * @author IvanWei玮 -- maste
 * @version 1.0
 * @DataTime 2025/4/12 22:45
 * @since 1.8
 */
@Primary
@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeDao typeDao;
    @Autowired
    private RedisTemplate<String, Type> redisTemplate;

    @PostConstruct
    public void init() {
        List<Type> all = typeDao.findAll();
        for (Type type : all) {
            redisTemplate.opsForHash().put("type", type.getId(), type);
        }
    }

    @Override
    public List<Type> findAll() {
        return typeDao.findAll();
    }

    @Override
    public Type findById(int id) {
        Object o = redisTemplate.opsForHash().get("type", id);
        Type t = (Type) o;
        if (t != null) {
            return t;
        }

        Type type = typeDao.findById(id);

        if (type != null) {
            redisTemplate.opsForHash().put("type", id, type);
        }

        return type;
    }

    @Override
    public int add(Type type) {
        redisTemplate.opsForHash().delete("type" , type.getId());
        int add = typeDao.add(type);
        redisTemplate.opsForHash().delete("type" , type.getId());

        return add;
    }

    @Override
    public int delete(Integer id) {
        redisTemplate.opsForHash().delete("type" , id);
        int delete = typeDao.delete(id);
        redisTemplate.opsForHash().delete("type" , id);
        return delete;
    }

    @Override
    public int update(Map<String, Object> map) {
        if (map.get("id") == null){
            return 0;
        }
        redisTemplate.opsForHash().delete("type" , map.get("id"));
        int update = typeDao.update(map);
        redisTemplate.opsForHash().delete("type" , map.get("id"));
        return update;
    }
}
